package com.itheima.service.BrandServiceimp;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.pojo.pageBean;
import com.itheima.service.BrandService;
import com.itheima.util.SqlSessionFactoryutils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class brandServiceimp implements BrandService {
    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryutils.getSqlSessionFactory();
    @Override
    public List<Brand> findAll() {
        //1.获取SqlSession实例
        SqlSession a = sqlSessionFactory.openSession();
        //3.获取BrandMapper代理 对象
        BrandMapper mapper = a.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.findAll();
        a.close();
        return brands;
    }
    @Override
    public void add(Brand brand)
    {
        SqlSession a=sqlSessionFactory.openSession();
        BrandMapper mapper=a.getMapper(BrandMapper.class);
        mapper.insert(brand);
        a.commit();
        a.close();
    }
    @Override
    public void delete(Integer id) {
        SqlSession a = sqlSessionFactory.openSession();
        BrandMapper mapper = a.getMapper(BrandMapper.class);
        mapper.delete(id);
        a.commit();
        a.close();
    }
    @Override
    public void update(Brand brand)
    {
        SqlSession a=sqlSessionFactory.openSession();
        BrandMapper mapper=a.getMapper(BrandMapper.class);
        mapper.update(brand);
        a.commit();
        a.close();
    }
    @Override
    public void deletebyids(int[] idss)
    {
        SqlSession a=sqlSessionFactory.openSession();
        BrandMapper mapper=a.getMapper(BrandMapper.class);
        mapper.deletebyids(idss);
        a.commit();
        a.close();
    }
    @Override
    public pageBean<Brand> findByPage(int start, int size)
    {

        SqlSession a=sqlSessionFactory.openSession();
        BrandMapper mapper=a.getMapper(BrandMapper.class);
        //计算开始索引
        start=(start-1)*size;
        List<Brand> brands=mapper.findByPage(start,size);
        int count=mapper.findCount();
        //封装pageBean
        pageBean<Brand> pageBean=new pageBean<>();
        pageBean.setRows(brands);
        pageBean.setTotalpage(count);
        a.close();
        return pageBean;
    }
    @Override
    public pageBean<Brand> findByCondition(int c,int b,Brand brand) {
        SqlSession a=sqlSessionFactory.openSession();
        BrandMapper mapper=a.getMapper(BrandMapper.class);
        //计算开始索引
        c=(c-1)*b;
        List<Brand> brands=mapper.findByCondition(c,b,brand);
        int count=mapper.findCountbycondition(brand);
        //封装pageBean
        pageBean<Brand> pageBean=new pageBean<>();
        pageBean.setRows(brands);
        pageBean.setTotalpage(count);
        a.close();
        return pageBean;
    }



}
